//
//  TTFileManager.m
//  WxIOSReaderForiPhone
//
//  Created by anzeinfo on 13-5-22.
//  Copyright (c) 2013年 anzeinfo. All rights reserved.
//

#import "TTFileManager.h"

#define CACHEPATH [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]

@implementation TTFileManager
+(TTFileManager *)sharedManager
{
    static TTFileManager *_sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedManager = [[TTFileManager alloc]init];
    });
    return _sharedManager;
}

-(BOOL)archiveFile:(id)objects named:(NSString *)filePath{
    return [NSKeyedArchiver archiveRootObject:objects toFile:filePath];
}

-(id)unarchiveFile:(NSString *)filePath{
    id temp = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    return temp;
}


//using type to create another full path for file.
- (NSString *)pathMaker:(NSString *)path fileType:(NSString *)type{
    NSString *fileName = [[[path lastPathComponent] stringByDeletingPathExtension] stringByAppendingString:type];
    NSString *fullPath = [CACHEPATH stringByAppendingPathComponent:fileName];
    return fullPath;
}

- (NSString *)filePathMaker:(NSString *)name fileType:(NSString *)type{
    return [CACHEPATH stringByAppendingPathComponent:[name stringByAppendingString:type]];
}


-(BOOL)deleteFile:(NSString *)path{
    if([[NSFileManager defaultManager]fileExistsAtPath:path]){
        NSError *error;
        [[NSFileManager defaultManager]removeItemAtPath:path error:&error];
        if(!error){
            return TRUE;
        }
    }
    return NO;
}

-(BOOL)fileExists:(NSString *)path{
    NSFileManager *TTFileManager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    if ([TTFileManager fileExistsAtPath:path isDirectory:&isDir]) {
        return YES;
	}
    return NO;
}

//设置文件不在 iCloud 备份
- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
    BOOL success = NO;
    if([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]){
        NSError *error = nil;
        success = [URL setResourceValue: [NSNumber numberWithBool: YES]
                                 forKey: NSURLIsExcludedFromBackupKey error: &error];
        if(!success){
            NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
        } else {
            NSString *toFilePath = [URL path];
            if ([[NSFileManager defaultManager] setAttributes:@{NSFileCreationDate:[NSDate date]} ofItemAtPath:toFilePath error:&error]) {
                NSLog(@"成功");
            } else {
                NSLog(@"失败");
            }
            NSLog(@"%@", [[[NSFileManager defaultManager] attributesOfItemAtPath:toFilePath error:nil] objectForKey:NSFileCreationDate]);
        }
    }
    return success;
}


@end
